package com.chao.gulimall.ssoserver.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;

@Slf4j
@Controller
public class LoginController {

    @Autowired
//    RedisTemplate redisTemplate;//有什么区别？？
    StringRedisTemplate stringRedisTemplate;

    @ResponseBody
    @GetMapping("/userInfo")
    public String userInfo(@RequestParam(value = "token") String token){
        return stringRedisTemplate.opsForValue().get(token);
    }

    @RequestMapping("login.html")
    public String loginPage(@RequestParam("redirect_url") String url, Model model,
                            @CookieValue(value = "sso_chao_token",required = false) String token){
        if(!StringUtils.isEmpty(token)){
            String s = stringRedisTemplate.opsForValue().get(token);//redis中校验 token是否存在，若获取不到s的值是null
            if(!StringUtils.isEmpty(s)){
                return "redirect:"+url+"?token="+token;//携带token 直接返回
            }
        }
        model.addAttribute("url",url);
        return "login";
    }

    @PostMapping("/doLogin")
    public String doLogin(@RequestParam("username") String username,
                          @RequestParam("password") String password,
                          @RequestParam("url") String url, Model model,
                          HttpServletResponse response){
        log.info("登录的用户名为：{}，密码：{}，登录成功后返回地址：{}",username,password,url);
        //登录成功，跳回之前的登录页面

        if(!StringUtils.isEmpty(username) && !StringUtils.isEmpty(password) ){
            //登录成功   跳转回之前页面
            //保存登录信息
            String token = UUID.randomUUID().toString().replace("-", "");
            stringRedisTemplate.opsForValue().set(token,username+"-"+password);
//            stringRedisTemplate.opsForSet().add("token",username+"-"+password);

            Cookie cookie = new Cookie("sso_chao_token",token);
            response.addCookie(cookie);

            return "redirect:"+url+"?token="+token;
        }else{
            //登录失败 跳转登录页面继续登录
            model.addAttribute("url",url);
            return "login";
        }


    }





}
